const Axios = require('axios');
const cheerio = require('cheerio');
const fs = require('fs')
const path = require('path')
const config = require('../config')
const Api ={
	getCatalogue: async url =>{
		let catalogue = []
		await Axios.get(url)
		.then(function (response) {
			let $ = cheerio.load(response.data);
			$(config.navDom).each((idx, ele) => {
				let text =$(ele).find('a').text()
				let href =$(ele).find('a').attr('href')
				catalogue.push({text:text, href:`https://www.yixuela.com${href}`})

			})
		})
		.catch(function (error) {
			console.log(error);
		})

		return catalogue

	},
	getImages: async (href, index)=>{
		let imgList = []
		await Axios.get(href)
		.then(function (response) {
			let $ = cheerio.load(response.data);
			$(config.imgDon).find('img').each((idx, ele) => {
				let src = $(ele).attr('src')
				let title = $(ele).attr('alt').replace(/(^.*册)_(.*)第(\d{1,2})页/g, ($1,$2,$3,$4)=>{
					return `${$3}_${$4.length == 1 ? `0${$4}` : $4 }`
				})
				imgList.push({src: src, name: `${index+1}_${idx+1}_${title}`})

			})
		})
		.catch(function (error) {
			console.log(error);
		})

		return imgList
	},
	download: async (imageSrc, name)=>{
		Axios.get(imageSrc, { params: 'param', responseType: 'arraybuffer'})
		.then(function (response) {

			let index = imageSrc.lastIndexOf(".");
			let suffix = imageSrc.substr(index+1);

			Api.saveFile(path.resolve(__dirname, `../catalogue/lesson/${name}.${suffix}`), response.data)

		})
		.catch(function (error) {
			console.log(`数据写入失败: ${name}`);

		})
	},
	saveFile: async (path, data)=>{
		fs.writeFile(path, data, function(err){
			if (err) {
			console.log(`数据写入失败: ${path}`);

				return console.error(err);
			}
			console.log("数据写入成功！");
		})
	}
} 


module.exports = Api